/*
 * DatabaseProgressPanel.java
 *
 * Created on November 23, 2008, 4:45 PM
 */
package com.bff.slimserver.musicjukebox.ui.database;

import com.bff.slimserver.musicjukebox.lib.JukeboxProperties;
import com.bff.bjj.ui.component.BJJPanel;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.SwingConstants;
import org.bff.slimserver.SlimDatabase;
import org.bff.slimserver.events.DatabaseScanEvent;
import org.bff.slimserver.events.DatabaseScanListener;
import org.bff.slimserver.exception.SlimConnectionException;
import org.bff.slimserver.musicobjects.SlimDatabaseProgress;

/**
 *
 * @author  Music
 */
public class DatabaseProgressPanel extends BJJPanel implements DatabaseScanListener {

    private SlimDatabase db;
    private List<ProgressPanel> progressPanels;
    private boolean scanning;

    /** Creates new form DatabaseProgressPanel */
    public DatabaseProgressPanel() {
        try {
            db = JukeboxProperties.getInstance().getDatabase();
        } catch (SlimConnectionException ex) {
            Logger.getLogger(DatabaseProgressPanel.class.getName()).log(Level.SEVERE, null, ex);
        }

        initComponents();

        progressPanels = new ArrayList<ProgressPanel>();


        if (db.isRescanning()) {
            for (SlimDatabaseProgress.Importer importer : db.getScanProgress().getImporters()) {
                ProgressPanel pp = new ProgressPanel(importer.getImporter());
                progressPanels.add(pp);
                progressPanel.add(pp);
                startScanThread();
            }

        }

        JukeboxProperties.getInstance().getSlimMonitor().addDatabaseScanListener(this);
    }

    public void setDone() {
        for(ProgressPanel pp : progressPanels) {
            pp.setDone();
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new BJJPanel();
        jLabel1 = new javax.swing.JLabel();
        lblTotalTime = new javax.swing.JLabel();
        progressPanel = new BJJPanel();
        lblInfo = new javax.swing.JLabel();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Rescan Progress"));
        setLayout(new java.awt.BorderLayout());

        jLabel1.setText("Total Time:");
        jPanel1.add(jLabel1);

        lblTotalTime.setText("jLabel1");
        jPanel1.add(lblTotalTime);

        add(jPanel1, java.awt.BorderLayout.NORTH);

        progressPanel.setLayout(new javax.swing.BoxLayout(progressPanel, javax.swing.BoxLayout.PAGE_AXIS));
        add(progressPanel, java.awt.BorderLayout.CENTER);

        lblInfo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblInfo.setText("Scan Info");
        add(lblInfo, java.awt.BorderLayout.PAGE_END);
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lblInfo;
    private javax.swing.JLabel lblTotalTime;
    private javax.swing.JPanel progressPanel;
    // End of variables declaration//GEN-END:variables

    private void startScanThread() {
        new Thread(new Runnable() {

            @Override
            public void run() {

                while (scanning) {
                    SlimDatabaseProgress sdp = db.getScanProgress();
                    lblTotalTime.setText(sdp.getTotalTime());

                    if(sdp.getInfo() == null) {
                        lblInfo.setVisible(false);
                    } else {
                        lblInfo.setVisible(true);
                        lblInfo.setText(sdp.getInfo());
                    }
                    for (SlimDatabaseProgress.Importer importer : sdp.getImporters()) {
                        boolean found = false;
                        for (ProgressPanel pp : progressPanels) {

                            if (pp.getImporter().equalsIgnoreCase(importer.getImporter())) {
                                pp.setProgress(importer.getPercentage());
                                found = true;
                            }
                        }

                        if (!found) {
                            ProgressPanel pp = new ProgressPanel(importer.getImporter());
                            progressPanels.add(pp);
                            progressPanel.add(pp);
                        }
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(DatabaseProgressPanel.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }).start();
    }
    // End of variables declaration

    private class ProgressPanel extends BJJPanel {

        private String importer;
        private JProgressBar progressBar;
        private JLabel lblPercent;

        public ProgressPanel(String importer) {
            setImporter(importer);
            setLayout(new GridBagLayout());

            JLabel lbl = new JLabel(importer +": ");
            lbl.setPreferredSize(new Dimension(200, 25));
            lbl.setHorizontalTextPosition(SwingConstants.TRAILING);
            lbl.setHorizontalAlignment(SwingConstants.TRAILING);
            GridBagConstraints gb = new GridBagConstraints();
            gb.gridx = 0;
            gb.gridy = 0;
            add(lbl, gb);

            progressBar = new JProgressBar(0, 100);
            progressBar.setPreferredSize(new Dimension(300, 15));
            gb.gridx = 1;
            gb.gridy = 0;
            add(progressBar, gb);

            lblPercent = new JLabel("   ");
            gb.gridx = 2;
            gb.gridy = 0;
            add(lblPercent, gb);
        }

        public String getImporter() {
            return importer;
        }

        public void setImporter(String importer) {
            this.importer = importer;
        }

        public void setProgress(int progress) {
            if(progress == -1) {
                progress = 0;
            }

            progressBar.setValue(progress);
            String s = Integer.toString(progress);
            while(s.length() < 3) { s = s + " "; }
            lblPercent.setText(" " + s  + "%");
        }

        private void setDone() {
            progressBar.setValue(100);
            lblPercent.setText(" 100%");
        }
    }

    @Override
    public void databaseScanEventReceived(DatabaseScanEvent event) {
        switch (event.getId()) {
            case DatabaseScanEvent.SCAN_STARTED:
                scanning = true;
                for (ProgressPanel pp : progressPanels) {
                    progressPanel.remove(pp);
                }

                progressPanels.clear();

                for (SlimDatabaseProgress.Importer importer : db.getScanProgress().getImporters()) {
                    ProgressPanel pp = new ProgressPanel(importer.getImporter());
                    progressPanels.add(pp);
                    progressPanel.add(pp);
                    startScanThread();
                }
                startScanThread();
                break;
            case DatabaseScanEvent.SCAN_ENDED:
                scanning = false;
                break;
        }
    }
}
